<template>
  <div class="ai-chat">
    <div class="chat-container">
      <div class="sidebar">
        <div class="history-header">
          <h2>聊天记录</h2>
          <el-button type="primary" size="small" @click="startNewChat">
            + 新对话
          </el-button>
        </div>
        <div class="history-list">
          <div 
            v-for="chat in chatHistory" 
            :key="chat.id"
            class="history-item"
            :class="{ 'active': currentChatId === chat.id }"
            @click="loadChat(chat.id)"
          >
            <el-icon><ChatDotRound /></el-icon>
            <span class="title">{{ chat.title }}</span>
          </div>
        </div>
      </div>
      
      <div class="chat-main">
        <div class="messages" ref="messagesRef">
          <div 
            v-for="(message, index) in currentMessages"
            :key="index"
            class="message"
            :class="message.role"
          >
            <div class="avatar">
              <el-icon v-if="message.role === 'user'"><User /></el-icon>
              <el-icon v-else><Cpu /></el-icon>
            </div>
            <div class="content">
              <div class="message-header">
                <span class="role-label">{{ message.role === 'user' ? '用户' : 'AI助手' }}</span>
              </div>
              <div class="message-content" v-html="formatMessage(message.content)"></div>
            </div>
          </div>
          <div v-if="isStreaming" class="message assistant">
            <div class="avatar">
              <el-icon><Cpu /></el-icon>
            </div>
            <div class="content">
              <div class="message-content">
                <span class="typing-indicator">正在思考中...</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="input-area">
          <div class="input-row">
            <div class="input-wrapper">
              <el-input
                v-model="userInput"
                type="textarea"
                :rows="1"
                :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="请输入您的问题..."
                @keydown.enter.prevent="handleEnter"
                ref="inputRef"
              />
            </div>
            <div class="send-wrapper">
              <el-button 
                type="primary"
                :icon="Position"
                circle
                @click="sendMessage"
                :disabled="isStreaming || !userInput.trim()"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { _aiChatStream } from '@/api/ai'
import { ElMessage } from 'element-plus'
import { ChatDotRound, User, Cpu, Position } from '@element-plus/icons-vue'

const messagesRef = ref(null)
const inputRef = ref(null)
const userInput = ref('')
const isStreaming = ref(false)
const currentChatId = ref('')
const currentMessages = ref([])
const chatHistory = ref([])

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 处理回车键
const handleEnter = (e) => {
  if (e.shiftKey) {
    // Shift + Enter 换行
    return
  }
  // Enter 发送消息
  e.preventDefault()
  sendMessage()
}

// 发送消息
const sendMessage = async () => {
  if (isStreaming.value) return
  if (!userInput.value.trim()) return
  
  if (!currentChatId.value) {
    startNewChat()
  }
  
  const messageContent = userInput.value.trim()
  
  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: messageContent,
    timestamp: new Date()
  }
  currentMessages.value.push(userMessage)
  
  // 清空输入
  userInput.value = ''
  await scrollToBottom()
  
  // 添加助手消息占位
  const assistantMessage = {
    role: 'assistant',
    content: '',
    timestamp: new Date()
  }
  currentMessages.value.push(assistantMessage)
  isStreaming.value = true
  
  try {
    const response = await _aiChatStream(messageContent, currentChatId.value)
    
    if (!response.ok) {
      throw new Error('请求失败')
    }
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let accumulatedContent = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value, { stream: true })
      accumulatedContent += chunk
      
      // 实时更新消息内容
      assistantMessage.content = formatContent(accumulatedContent)
      await scrollToBottom()
    }

    // 保存到当前会话
    const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
    if (currentChat) {
      currentChat.messages = [...currentMessages.value]
      // 更新标题为第一条用户消息的前10个字符
      if (currentChat.messages.length === 2) {
        currentChat.title = currentChat.messages[0].content.slice(0, 10) + '...'
      }
    }
    
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请稍后重试')
    assistantMessage.content = '抱歉，发生了错误，请稍后重试。'
  } finally {
    isStreaming.value = false
    await scrollToBottom()
  }
}

// 格式化内容（简单的换行处理）
const formatContent = (content) => {
  if (!content) return ''
  return content
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
}

// 格式化消息（兼容模板调用）
const formatMessage = (content) => {
  return formatContent(content)
}

// 加载特定对话
const loadChat = (chatId) => {
  // 保存当前会话
  if (currentChatId.value && currentMessages.value.length > 0) {
    const oldChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
    if (oldChat) {
      oldChat.messages = [...currentMessages.value]
    }
  }

  currentChatId.value = chatId
  const targetChat = chatHistory.value.find(chat => chat.id === chatId)
  
  if (targetChat?.messages) {
    currentMessages.value = [...targetChat.messages]
  } else {
    currentMessages.value = []
  }
  
  scrollToBottom()
}

// 开始新对话
const startNewChat = () => {
  const newChatId = Date.now().toString()
  
  // 保存当前会话到历史记录
  if (currentChatId.value && currentMessages.value.length > 0) {
    const oldChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
    if (oldChat) {
      oldChat.messages = [...currentMessages.value]
    }
  }
  
  currentChatId.value = newChatId
  currentMessages.value = []
  
  const newChat = {
    id: newChatId,
    title: `新对话`,
    messages: []
  }
  chatHistory.value = [newChat, ...chatHistory.value]
  
  console.log('创建新对话:', newChatId)
}

onMounted(() => {
  // 初始化时创建一个新对话
  startNewChat()
})
</script>

<style lang="scss" scoped>
.ai-chat {
  position: fixed;
  top: 64px;
  left: 240px;
  right: 0;
  bottom: 0;
  display: flex;
  background: #f0f2f5;
  overflow: hidden;
  z-index: 1;

  .chat-container {
    flex: 1;
    display: flex;
    width: 100%;
    margin: 0 auto;
    padding: 1rem;
    gap: 1rem;
    height: 100%;
    overflow: hidden;
  }

  .sidebar {
    width: 250px;
    display: flex;
    flex-direction: column;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    
    .history-header {
      flex-shrink: 0;
      padding: 1rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      
      h2 {
        font-size: 16px;
        color: #333;
        margin: 0;
        font-weight: 500;
      }
    }
    
    .history-list {
      flex: 1;
      overflow-y: auto;
      padding: 0.5rem;
      
      .history-item {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        color: #666;
        margin-bottom: 4px;
        
        &:hover {
          background: #f5f5f5;
        }
        
        &.active {
          background: #e6f2ff;
          color: #1890ff;
        }
        
        i {
          font-size: 16px;
        }
        
        .title {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 14px;
        }
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .messages {
      flex: 1;
      overflow-y: auto;
      padding: 1.5rem;
      background: #f5f7f9;
      
      .message {
        display: flex;
        gap: 1rem;
        margin-bottom: 1.5rem;
        
        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
          background: #f0f2f5;
          
          i {
            font-size: 20px;
            color: #666;
          }
        }
        
        &.user {
          flex-direction: row-reverse;
          
          .content {
            align-items: flex-end;
            
            .message-header {
              justify-content: flex-end;
            }
            
            .message-content {
              background: #95ec69;
              border-radius: 4px 0 4px 4px;
              color: #000;
            }
          }
          
          .avatar {
            background: #e6f7ff;
            
            i {
              color: #1890ff;
            }
          }
        }
        
        &.assistant {
          .avatar {
            background: #f6f6f6;
            
            i {
              color: #666;
            }
          }
          
          .content .message-content {
            background: #fff;
            border-radius: 0 4px 4px 4px;
            color: #000;
          }
        }
        
        .content {
          display: flex;
          flex-direction: column;
          gap: 0.25rem;
          max-width: 70%;
          
          .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            
            .role-label {
              font-size: 12px;
              color: #999;
            }
          }
          
          .message-content {
            padding: 0.75rem 1rem;
            font-size: 14px;
            line-height: 1.6;
            white-space: pre-wrap;
            word-wrap: break-word;
            
            .typing-indicator {
              display: inline-block;
              animation: pulse 1.5s ease-in-out infinite;
            }
            
            :deep(strong) {
              font-weight: 600;
              color: #333;
            }
            
            :deep(em) {
              font-style: italic;
              color: #666;
            }
            
            :deep(br) {
              display: block;
              content: "";
              margin: 0.5em 0;
            }
          }
        }
      }
    }
    
    .input-area {
      flex-shrink: 0;
      padding: 1rem;
      background: #fff;
      border-top: 1px solid #eee;

      .input-row {
        display: flex;
        align-items: flex-end;
        gap: 0.75rem;
        background: #fff;

        .input-wrapper {
          flex: 1;
          
          :deep(.el-textarea) {
            .el-textarea__inner {
              background: #f5f7f9;
              border: none;
              border-radius: 4px;
              padding: 10px 12px;
              font-size: 14px;
              line-height: 1.5;
              resize: none;
              
              &:focus {
                background: #fff;
                border: 1px solid #1890ff;
              }
            }
          }
        }

        .send-wrapper {
          :deep(.el-button) {
            width: 40px;
            height: 40px;
          }
        }
      }
    }
  }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@media (max-width: 768px) {
  .ai-chat {
    left: 0;
    top: 50px;
    
    .chat-container {
      padding: 0;
    }
    
    .sidebar {
      display: none;
    }
    
    .chat-main {
      border-radius: 0;
    }
  }
}
</style> 